const express = require('express');
const router = express.Router();
const fs = require('fs');
const ejs = require('ejs');
const cookieParse = require('cookie-parser');
const JWT = require('jsonwebtoken');
const { expressjwt } = require('express-jwt');
const secretKey = 'zhe shi mi yao ^-^';
router.use(cookieParse());
router.get('/login', (req, res) => {
  ejs.renderFile('./views/login.html', {}, (err, str) => {
    res.send(str);
  });
});
router.get('/', (req, res) => {
  let token = req.cookies.token;
  try {
    let userData = JWT.verify(token, secretKey);
    ejs.renderFile(
      './public/index.ejs',
      { data: '欢迎' + userData.name },
      (err, data) => {
        res.send(data);
      }
    );
  } catch {
    ejs.renderFile('./public/index.ejs', { data: '未登录' }, (err, data) => {
      res.send(data);
    });
  }
});

router.post('/login', (req, res) => {
  let { username: name, password: pwd } = req.body;
  fs.readFile('./userlists.txt', 'utf-8', (err, data) => {
    let userlists = JSON.parse(data);
    for (let i = 0; i < userlists.length; i++) {
      if (userlists[i].name == name) {
        if (userlists[i].pwd == pwd) {
          let token = JWT.sign({ name }, secretKey, { expiresIn: '30s' });
          res.cookie('token', token, {
            maxAge: 1000 * 60 * 60 * 24 * 10,
            httpOnly: true,
          });
          res.redirect('/');
          return;
        } else {
          res.send('密码错误');
          return;
        }
      }
    }
    res.send('未注册');
    return;
  });
});
router.get('/register', (req, res) => {
  ejs.renderFile('./views/register.html', {}, (err, str) => {
    res.send(str);
  });
});
router.post('/register', (req, res) => {
  let { username: name, password: pwd } = req.body;
  fs.readFile('./userlists.txt', 'utf-8', (err, data) => {
    let userlist = JSON.parse(data);
    for (let i = 0; i < userlist.length; i++) {
      if (userlist[i].name == name) {
        res.send('该账号已经注册');
        return;
      }
    }
    userlist.push({ name, pwd });
    fs.writeFile('./userlists.txt', JSON.stringify(userlist), (err) => {
      if (err) {
        res.send('出错了');
      } else {
        res.send('注册成功');
      }
    });
  });
});

module.exports = router;
